const express = require('express');
const mockdb = require('@andremao/mockdb');
const jwt = require('jsonwebtoken');
const fs = require('fs');

const SECRET_KEY = fs.readFileSync('./secret.key').toString().trim();

console.log(SECRET_KEY, 'SECRET_KEY');

const userService = mockdb.service('user.json');

const app = express();

app.get('/', (req, res) => {
  res.send('ok');
});

app.post('/reg', express.json(), (req, res) => {
  userService.create(req.body);
  res.send('reg ok');
});

app.post('/login', express.json(), (req, res) => {
  const user = userService
    .getState()
    .list.find((v) => v.uname === req.body.uname && v.upwd === req.body.upwd);
  const access_token = jwt.sign({ uid: user.id }, SECRET_KEY, {
    expiresIn: '30m',
  });
  res.json({
    code: 200,
    msg: 'ok',
    access_token,
  });
});

app.get('/profile', (req, res) => {
  const access_token = req.headers.authorization.split(' ')[1];
  try {
    const payload = jwt.verify(access_token, SECRET_KEY);
    console.log(payload, 'payload');
    res.send('profile ok');
  } catch (e) {
    res.json({
      code: 401,
      msg: 'invalid token',
    });
  }
});

app.listen(3000);
